package com.bl.student.service.biz.file.impl;

import com.bl.student.common.utils.EncodeUtils;
import com.bl.student.service.biz.file.FileService;
import com.bl.student.common.ApiResponseCode;
import com.bl.student.common.CommonServiceException;
import com.bl.student.service.config.FileConfig;
import com.bl.student.service.vo.file.FileInfoVo;
import lombok.extern.log4j.Log4j2;
import org.aeonbits.owner.ConfigFactory;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Created by yujingyi on 2017/6/19.
 */
@Log4j2
@Service
public class FileServiceImpl implements FileService {

    final private String MENTOR_DEFAULT_PATH = "/default/mentor.jpeg";

    static private FileConfig fileConfig = ConfigFactory.create(FileConfig.class);

    public FileInfoVo upload(MultipartFile file, String account) {
        FileInfoVo fileInfoVo = new FileInfoVo();

        //获取文件名
        String fileName = EncodeUtils.MD5(file.getOriginalFilename(), "utf-8").toLowerCase() + System.currentTimeMillis();
//        String fileName = Generator.generateFileName(fileName);

        String uploadPath = generateUploadPath(fileName, account);
        doUpload(uploadPath, file);

        fileInfoVo.setUrl(generateFileDisplayUrl(fileName, account));
        fileInfoVo.setName(fileName);

        return fileInfoVo;
    }

    public void doUpload(String path, MultipartFile file) {
        log.info("upload file.... fileName: {}, path: {}", file.getName(), path);
        File uploadFile = new File(path);
        try {
            //存储文件
            file.transferTo(uploadFile);
            uploadFile.setReadable(true, false);
            uploadFile.setExecutable(true, false);
        } catch (Exception e) {
            e.printStackTrace();
            log.error(e.getMessage());
            throw new CommonServiceException(ApiResponseCode.SYSTEM_ERROR.getCode(), "文件存储失败");
        }
    }

    public String generateUploadPath(String fileName, String account) {
        StringBuilder userDirPath = new StringBuilder();

        userDirPath.append(fileConfig.uploadPath())
                .append("/")
                .append(account)
                .append("/");
//        userDirPath.append("/Users/sora/WorkSpace/tmp")
//                .append("/")
//                .append(account)
//                .append("/");

        // if user directory does not exist, make
        File userDir = new File(userDirPath.toString());
        if (!userDir.exists() && !userDir.isDirectory()) {
            userDir.mkdir();
            userDir.setExecutable(true, false);
            userDir.setReadable(true, false);
        } else if (userDir.exists() && !userDir.isDirectory()) {
            log.error("{} is not a url!", userDirPath.toString());
            throw new CommonServiceException(ApiResponseCode.SYSTEM_ERROR.getCode(), "文件路径生成失败");
        }

        userDirPath.append(fileName);

        return userDirPath.toString();
    }

    public String generateFileDisplayUrl(String fileName, String account) {
//        if (imgName == null || StringUtils.isBlank(imgName)) {
//            return getDefualImgUrl();
//        }

        StringBuilder userDirPath = new StringBuilder();
        userDirPath.append(fileConfig.displayPath())
                .append("/").append(account).append("/");
        userDirPath.append(fileName);

        return userDirPath.toString();
    }

    public String getMentorDefaultUrl() {

        StringBuilder builder = new StringBuilder();
        builder.append(fileConfig.displayPath())
                .append(MENTOR_DEFAULT_PATH);

        return builder.toString();
    }

    private String getFileName(String url) {
        Pattern pattern = Pattern.compile("\\/(\\w+)\\/(\\w+)$");
        Matcher matcher = pattern.matcher(url);

        if (matcher.find()) {
            return matcher.group(0);
        } else {
            return null;
        }
    }

//    public void deleteImg(String imgId, AuthInfo authInfo) {
//
//
//        String fileName = getImgFileName(imgFile);
//        StringBuilder builder = new StringBuilder()
//                .append(Constants.IMG_UPLOAD_PATH)
//                .append("/")
//                .append(fileName);
//
//        log.info("delete img file: " + builder.toString());
//        File file = new File(builder.toString());
//        log.info("img file is exist: " + file.exists());
//        file.delete();
//    }
}
